//
//  OAuthViewController.swift
//  weibo-mxm
//
//  Created by 马晓敏 on 16/1/12.
//  Copyright © 2016年 马晓敏. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
     let webView = UIWebView()
    
    
    @objc private func close(){
    //dismiss页面
      dismissViewControllerAnimated(true, completion: nil)
    
    
    }
    //自动填充账号
    @objc private func  defaultCouunt() {
    let jsString = "document.getElementById('userId').value = '13718891476', document.getElementById('passwd').value = 'MXM19890718'"
    
    webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
     override   func loadView() {
    
       view = webView
        
       webView.delegate = self
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
     //只针对当前的导航视图控制器有效
    //   navigationController?.navigationBar.tintColor = UIColor.orangeColor()
 //一经设置,全局有效
//     UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
       print(view)
//设置导航条 
       setNavNar()
        
         loadOAuthPage()
}
    
    
    private func setNavNar(){
    
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
   self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style:.Plain, target: self, action: "defaultCouunt")
    
    }
    
  //MARK:加载授权页面
    private func loadOAuthPage(){
    //获取url
      let urlString  = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        
       let url = NSURL(string: urlString)!

    
       let request = NSURLRequest(URL: url)
     
        webView.loadRequest(request)
    }
    
    
}
//这样写,是将一类的协议办法,写在一起,更加好阅读和维护
//同一类的协议方法,就被放在一个扩展中

extension OAuthViewController:UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        
    SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
      
        SVProgressHUD.dismiss()
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL?.absoluteString)
        guard let urlString = request.URL?.absoluteString else{
        
        return false
        
        }
        
        if urlString.containsString("code="){
            print(urlString)
        //将url中的参数获取到
    guard  let query = request.URL?.query else {
            
              return false
            }
//        print(quer

       let codeStr = "code="
//将query转为NSString subString
        let code = (query as NSString).substringFromIndex(codeStr.characters.count)
        loadAccessToken(code)
      //
        print(code,query)
           //不希望页面跳转到回调页面
            return false
        }
        
        return  true
    }

    private func  loadAccessToken (code:String){
    
    UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
        if !isSuccess{
        
        print("用户登录失败")
        SVProgressHUD.showErrorWithStatus("网络连接有误,请稍后在试")
        return
        
        }
        
       //一定登录成功
        SVProgressHUD.showSuccessWithStatus("登录成功")
        self.dismissViewControllerAnimated(true, completion: nil)
        
        
        }
    
    }
}